<template>
  <el-upload
    ref="uploadImgRef"
    class="upload-box"
    :class="{ limit: fileList.length >= limit, hide: hideFile }"
    action="#"
    :drag="drag"
    :accept="accept"
    :file-list="fileList"
    :auto-upload="true"
    :limit="limit"
    :list-type="listType"
    :on-remove="handleFileRemove"
    :http-request="handleUploadRequest"
    :before-upload="handleBeforeFileUpload"
    :on-preview="handlePictureCardPreview"
  >
    <el-icon v-if="listType === 'picture-card'">
      <Plus />
    </el-icon>
    <el-button v-else type="primary">{{ uploadText }}</el-button>
  </el-upload>
</template>
<script setup lang="ts" name="BaseUpload">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { api as viewerApi } from 'v-viewer'
import { fileUploadApi } from '@/api/upload'
export interface UploadComponentProps {
  uploadText?: string
  hideFile?: boolean
  drag?: boolean
  modelValue: string
  listType?: string
  headers?: Record<string, string>
  data?: Record<string, any>
  accept?: string
  limit?: number
  maxSize?: number
}

const emits = defineEmits(['update:modelValue'])
const props = withDefaults(defineProps<UploadComponentProps>(), {
  modelValue: '',
  listType: 'picture-card',
  accept: 'image/*',
  limit: 1,
  maxSize: 2
})
const ip = computed(() => import.meta.env.VITE_BASE_API)

const fileList = ref<UploadUserFile[]>([])
watch(
  () => props.modelValue,
  val => {
    fileList.value = []
    if (val) {
      fileList.value =
        val.split(',')?.map(item => ({
          name: item,
          url: ip.value + item
        })) || []
    }
  },
  { immediate: true }
)
const handlePictureCardPreview = file => {
  const lastIndex = file?.name.lastIndexOf('.') || 0
  const extension = file?.name.slice(lastIndex + 1)
  if (!['gif', 'png', 'jpeg', 'jpg'].includes(extension)) {
    ElMessage.warning('无法在线预览此格式文件')
    return
  }
  viewerApi({
    options: { initialViewIndex: 0 },
    images: [file.url]
  })
}

const handleBeforeFileUpload = file => {
  const largeSize = 1024 * 1024 * props.maxSize
  if (file.size > largeSize) {
    ElMessage.error(`文件大小不能超过${props.maxSize}MB!`)
    return false // 阻止文件上传
  }
  return true // 允许文件上传
}
const handleUploadRequest = async option => {
  try {
    const formData = new FormData()
    formData.append('file', option.file)
    const { code, data } = await fileUploadApi(formData)
    if ((code === 0 || code === 200) && data) {
      ElMessage.success('上传成功')
      fileList.value.push({
        name: option.file.name,
        url: data
      })
      const url = fileList.value.map(item => item.url?.replace(ip.value, ''))?.join(',')
      emits('update:modelValue', url)
    }
  } catch (e) {
    console.log(e)
  }
  return true
}
const handleFileRemove = e => {
  console.log(JSON.stringify(fileList.value), e)
  const index = fileList.value.findIndex(item => item.name === e.name)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }
  console.log(JSON.stringify(fileList.value))
  const url = fileList.value.map(item => item.url?.replace(ip.value, ''))?.join(',')
  emits('update:modelValue', url)
}
</script>

<style lang="scss">
.upload-box.limit {
  .el-upload-list .el-upload {
    display: none !important;
  }
}
</style>
